package com.lubase.metadata.tabletrigger;

import com.lubase.model.DbEntity;
import com.lubase.model.DbField;
import com.lubase.model.DbTable;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.orm.extend.ITableTrigger;
import com.lubase.orm.util.TypeConverterUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class MtColumnTrigger implements ITableTrigger {
    @Override
    public String getTriggerTableCode() {
        return "mt_column";
    }

    @Override
    public String getTriggerName() {
        return "mt_column";
    }

    @Override
    public Boolean isEdit() {
        return true;
    }

    @Override
    public Boolean beforeValidate(DbTable tableInfo, DbEntity entity, Boolean isServer) throws Exception {
        String columnCode = entity.get("column_code").toString();
        String columnName = TypeConverterUtils.object2String(entity.get("column_name"), "");
        String aliasName = TypeConverterUtils.object2String(entity.get("alias_name"), "");
        if (!StringUtils.isEmpty(aliasName)) {
            entity.put("merge_name", aliasName);
        } else if (!StringUtils.isEmpty(columnName)) {
            entity.put("merge_name", columnName);
        } else {
            entity.put("merge_name", columnCode);
        }

        Integer isCodeData = TypeConverterUtils.object2Integer(entity.get("codedata_tag"), 0);
        if (isCodeData == 1) {
            String memo = TypeConverterUtils.object2String(entity.get("memo"), "");
            DbField memoField = tableInfo.firstOrDefault(x -> x.getCode().equals("memo"));
            if (StringUtils.isEmpty(memo)) {
                throw new WarnCommonException(String.format("码表字段  %s 的值不能为空", memoField.getName()));
            }
        }
        return true;
    }
}
